/*
 * @Descripttion:
 * @Version: 1.0
 * @Author: zyh
 * @Date: 2025-08-07 14:11:22
 * @LastEditors: Muxi 916566446@qq.com
 * @LastEditTime: 2025-08-22 11:27:51
 */
import 'dart:math';
import 'package:app_core/app_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import '../app/config.dart';

/// 消息类型枚举
enum MsgType {
  normal, // 普通消息
  success, // 成功消息
  error, // 错误消息
  warning, // 警告消息
}

class YHSmartDialog {
  /// 防抖控制：记录最后一次显示时间
  static DateTime? _lastToastTime;

  /// 防抖时间间隔：200ms 内不允许重复显示
  static const Duration _toastDebounceTime = Duration(milliseconds: 200);

  /// 计算显示时间
  static Duration _msgDuration(String message) {
    var isCn = Get.locale?.countryCode == "zh";
    return Duration(milliseconds: min(1500 + max(message.length - 10, 0) * (isCn ? 200 : 20), 5000));
  }

  /// 检查是否需要防抖
  static bool _shouldDebounceToast() {
    if (_lastToastTime == null) return false;
    return DateTime.now().difference(_lastToastTime!) < _toastDebounceTime;
  }

  /// 更新最后显示时间
  static void _updateLastToastTime() => _lastToastTime = DateTime.now();

  /// 安全的显示 toast
  static Future<void> _safeShowToast(String message, {Alignment alignment = Alignment.center}) async {
    try {
      return SmartDialog.showToast(
        message,
        alignment: alignment,
        displayTime: _msgDuration(message),
        builder: (context) => Padding(padding: _getMarginWithAlignment(alignment), child: appGlobalConfig.dialogConfig.toastWidget(message)),
      );
    } catch (e) {
      _lastToastTime = null;
      SmartDialog.dismiss();
      debugPrint('toast 失败: $e');
    }
  }

  /// 统一的 toast 显示方法（带防抖）
  static Future<void> _showToastWithDebounce(String message, {Alignment alignment = Alignment.center, MsgType msgType = MsgType.normal}) async {
    if (_shouldDebounceToast()) return;
    try {
      if (SmartDialog.checkExist()) {
        SmartDialog.dismiss();
        await Future.delayed(Duration(milliseconds: 50));
      }
    } catch (e) {
      debugPrint('清理 SmartDialog 失败: $e');
    }
    _updateLastToastTime();
    appGlobalConfig.dialogConfig.currentMsgType = msgType;
    return _safeShowToast(message, alignment: alignment);
  }

  /// ==================== toast 通知功能 ====================
  /// 显示普通信息（带防抖）
  static Future<void> showMsg(String message, {Alignment alignment = Alignment.center}) async {
    return _showToastWithDebounce(message, alignment: alignment, msgType: MsgType.normal);
  }

  /// 显示成功消息（带成功图标，居中显示）
  static Future<void> showSuccessMsg(String message) async {
    return _showToastWithDebounce(message, alignment: Alignment.center, msgType: MsgType.success);
  }

  /// 显示错误消息（带错误图标，居中显示）
  static Future<void> showErrorMsg(String message) async {
    return _showToastWithDebounce(message, alignment: Alignment.center, msgType: MsgType.error);
  }

  /// 显示警告消息（带警告图标，居中显示）
  static Future<void> showWarningMsg(String message) async {
    return _showToastWithDebounce(message, alignment: Alignment.center, msgType: MsgType.warning);
  }

  static EdgeInsets _getMarginWithAlignment(Alignment alignment) {
    if (alignment == Alignment.topCenter || alignment == Alignment.topLeft || alignment == Alignment.topRight) {
      return EdgeInsets.only(top: ScreenAdapter.appBarStatusBarHeight);
    }
    if (alignment == Alignment.bottomCenter || alignment == Alignment.bottomLeft || alignment == Alignment.bottomRight) {
      return EdgeInsets.only(bottom: 64);
    }
    return EdgeInsets.zero;
  }

  /// 显示加载中
  static Future showLoading({String? message, bool cancelable = true}) {
    return SmartDialog.showLoading(msg: message ?? "", maskColor: Colors.transparent, clickMaskDismiss: cancelable);
  }

  /// 统一关闭 loading
  static Future<void> dismiss({bool force = false}) {
    return SmartDialog.dismiss(status: SmartStatus.loading, force: force);
  }

  // ==================== Notify 通知功能 ====================
  /// 显示顶部成功通知（使用自定义样式）
  static Future<void> showTopSuccessNotify(String message) {
    return SmartDialog.showNotify(msg: message, notifyType: NotifyType.success, displayTime: _msgDuration(message), alignment: Alignment.topCenter);
  }

  /// 显示顶部错误通知（使用自定义样式）
  static Future<void> showTopErrorNotify(String message) {
    return SmartDialog.showNotify(msg: message, notifyType: NotifyType.error, displayTime: _msgDuration(message), alignment: Alignment.topCenter);
  }

  /// 显示顶部警告通知（使用自定义样式）
  static Future<void> showTopWarningNotify(String message) {
    return SmartDialog.showNotify(msg: message, notifyType: NotifyType.warning, displayTime: _msgDuration(message), alignment: Alignment.topCenter);
  }

  /// 显示顶部提醒通知（使用自定义样式）
  static Future<void> showTopAlertNotify(String message) {
    return SmartDialog.showNotify(msg: message, notifyType: NotifyType.alert, displayTime: _msgDuration(message), alignment: Alignment.topCenter);
  }

  /// 显示顶部失败通知（使用自定义样式）
  static Future<void> showTopFailureNotify(String message) {
    return SmartDialog.showNotify(msg: message, notifyType: NotifyType.failure, displayTime: _msgDuration(message), alignment: Alignment.topCenter);
  }

  /// 显示自定义通知条
  static Future<void> showCustomNotify({
    required Widget child,
    NotifyType type = NotifyType.success,
    Duration? duration,
    Alignment alignment = Alignment.topCenter,
    bool clickMaskDismiss = false,
  }) {
    return SmartDialog.showNotify(
      msg: "",
      builder: (context) => child,
      notifyType: type,
      displayTime: duration ?? _msgDuration(''),
      alignment: alignment,
      clickMaskDismiss: clickMaskDismiss,
    );
  }

  /// ==================== 对话框功能 ====================

  /// 显示确认对话框
  /// [title] 标题
  /// [content] 内容
  /// [confirmText] 确认按钮文字，默认"确定"
  /// [cancelText] 取消按钮文字，默认"取消"
  /// [confirmColor] 确认按钮颜色
  /// [showCancel] 是否显示取消按钮，默认true
  /// [barrierDismissible] 控制用户是否可以通过点击对话框外的遮罩层（半透明黑色背景）来关闭对话框。
  /// 返回值：true-确认，false-取消，null-点击遮罩关闭
  static Future<bool?> showConfirm({
    required String title,
    required String content,
    String confirmText = "确定",
    String cancelText = "取消",
    Color? confirmColor,
    bool showCancel = true,
    bool barrierDismissible = true,
  }) {
    return Get.dialog<bool>(
      _buildConfirmDialog(title: title, content: content, confirmText: confirmText, cancelText: cancelText, confirmColor: confirmColor, showCancel: showCancel),
      barrierDismissible: barrierDismissible,
    );
  }

  /// 显示警告对话框
  static Future<bool?> showWarningDialog({
    required String title,
    required String content,
    String confirmText = "知道了",
    String cancelText = "取消",
    bool showCancel = false,
    bool barrierDismissible = true,
  }) {
    return showConfirm(
      title: title,
      content: content,
      confirmText: confirmText,
      cancelText: cancelText,
      confirmColor: appGlobalConfig.dialogConfig.warningBtnColor,
      showCancel: showCancel,
      barrierDismissible: barrierDismissible,
    );
  }

  /// 显示危险操作确认对话框
  static Future<bool?> showDangerConfirm({
    required String title,
    required String content,
    String confirmText = "确认操作",
    String cancelText = "取消",
    bool barrierDismissible = true,
  }) {
    return showConfirm(
      title: title,
      content: content,
      confirmText: confirmText,
      cancelText: cancelText,
      confirmColor: appGlobalConfig.dialogConfig.errorBtnColor,
      showCancel: true,
      barrierDismissible: barrierDismissible,
    );
  }

  /// 显示信息对话框（只有确定按钮）
  static Future<bool?> showInfo({required String title, required String content, String confirmText = "知道了", bool barrierDismissible = true}) {
    return showConfirm(title: title, content: content, confirmText: confirmText, showCancel: false, barrierDismissible: barrierDismissible);
  }

  /// 构建确认对话框  这个可以自定义实现
  static Widget _buildConfirmDialog({
    required String title,
    required String content,
    required String confirmText,
    required String cancelText,
    Color? confirmColor,
    required bool showCancel,
  }) {
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Container(
        // width: 300,
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(title, style: appGlobalConfig.dialogConfig.dialogTitleStyle),
            const SizedBox(height: 16),
            Text(content, style: appGlobalConfig.dialogConfig.dialogContentStyle, textAlign: TextAlign.center),
            const SizedBox(height: 24),
            Row(
              children: [
                if (showCancel) ...[
                  Expanded(
                    child: OutlinedButton(
                      onPressed: () => Get.back(result: false),
                      style: OutlinedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        side: BorderSide(color: appGlobalConfig.dialogConfig.dividerColor),
                      ),
                      child: Text(cancelText),
                    ),
                  ),
                  const SizedBox(width: 12),
                ],
                Expanded(
                  child: ElevatedButton(
                    onPressed: () => Get.back(result: true),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: confirmColor ?? appGlobalConfig.dialogConfig.confirmBtnColor,
                      padding: const EdgeInsets.symmetric(vertical: 12),
                    ),
                    child: Text(confirmText, style: TextStyle(color: appGlobalConfig.dialogConfig.buttonTextColor)),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
